const path = require('path')
const loaderUtils = require('loader-utils');
const compilerSFC = require('@vue/compiler-sfc');


module.exports = function (resoures) {
  let { resourcePath } = this;
  const sfc = compilerSFC.parse(resoures);

  // 兼容windows的斜杠
  if (resourcePath) {
    resourcePath = resourcePath.split(path.sep).join('/');
  }

  function loaderPath($loader, $path) {
    const result = loaderUtils.stringifyRequest($loader, `${path.resolve(__dirname, $path)}`);
    return result.replace(/\"/g, '');
  }

  const scriptImport = (
    `var script = require('!${loaderPath(this, './script.js')}!babel-loader!${loaderPath(this, './selector.js')}?type=script!${resourcePath}')`
  );

  const templateImport = (
    `var template = require('!${loaderPath(this, './template.js')}!${loaderPath(this, './selector.js')}?type=template!${resourcePath}')`
  );

  var styleImports = [];
  if (Array.isArray(sfc.descriptor.styles)) {
    for (let i = 0; i < sfc.descriptor.styles.length; i++) {
      const sfcStyle = sfc.descriptor.styles[i];
      var styleloaders = [loaderPath(this, './style.js'), 'css-loader'];
      const { lang } = sfcStyle.attrs;
      const styleLoaderName = lang ? `${lang}-loader` : '';
      if (styleLoaderName) {
        styleloaders.push(styleLoaderName)
      }
      styleloaders.push(loaderPath(this, './selector.js'));
      const stylesLoaderPath = styleloaders.join('!');

      const styleImport = (
        `require('!${stylesLoaderPath}?type=style&index=${i}!${resourcePath}').default[0][1]`
      );
      styleImports.push(styleImport);
    }
  }
  const styleContents = `[${styleImports.join(',\n')}].join(' ')`;

  const componentImport = (
    `var components = require('!${loaderPath(this, './component.js')}!${resourcePath}')`
  );

  return `
    ${scriptImport}
    ${templateImport}
    ${componentImport}

    module.exports = {
      template: template(),
      ready: script.default,
      styles: ${styleContents},
      components: components(),
    };
  `;
};